package com.baibei.ebec.home.pirceFloat;

        import android.content.Intent;
        import android.os.Bundle;
        import android.support.v4.content.res.ResourcesCompat;
        import android.support.v7.app.AppCompatActivity;
        import android.util.Log;
        import android.util.SparseArray;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        import com.alibaba.android.arouter.facade.annotation.Route;
        import com.baibei.ebec.home.BuildConfig;
        import com.baibei.ebec.home.R;
        import com.baibei.ebec.home.R2;
        import com.baibei.ebec.quotation.QuotationManager;
        import com.baibei.ebec.quotation.event.IQuotationEvent;
        import com.baibei.ebec.sdk.ApiFactory;
        import com.baibei.ebec.sdk.IProductApi;
        import com.baibei.ebec.sdk.ITradeApi;
        import com.baibei.model.BaseHttpResponse;
        import com.baibei.model.FloatPriceInfo;
        import com.baibei.model.HomeIndexInfo;
        import com.baibei.model.NewHomeIndexInfo;
        import com.baibei.model.QuotationInfo;
        import com.baibei.model.UserInfo;
        import com.baibei.module.AppRouter;
        import com.baibei.quotation.QuotationFilter;
        import com.baibei.sdk.ApiDefaultObserver;
        import com.baibei.sdk.RxObservable;
        import com.blankj.utilcode.utils.LogUtils;
        import com.blankj.utilcode.utils.ToastUtils;
        import com.blankj.utilcode.utils.Utils;
        import com.google.gson.Gson;
        import com.rae.swift.Rx;
        import com.rae.swift.session.SessionManager;

        import org.greenrobot.eventbus.Subscribe;
        import org.json.JSONException;
        import org.json.JSONObject;

        import java.io.IOException;
        import java.math.BigDecimal;
        import java.math.RoundingMode;
        import java.util.HashMap;

        import butterknife.BindView;
        import butterknife.ButterKnife;
        import butterknife.OnClick;
        import okhttp3.Call;
        import okhttp3.FormBody;
        import okhttp3.MediaType;
        import okhttp3.OkHttpClient;
        import okhttp3.Request;
        import okhttp3.RequestBody;
        import okhttp3.Response;

@Route(path = AppRouter.ROUTE_PRICE_FLOAT)
public class PriceFloatActivity extends AppCompatActivity implements IQuotationEvent {

    @BindView(R2.id.tv_price_new)
    TextView tvPriceNew;
    @BindView(R2.id.tv_product_name)
    TextView tvProductName;
    @BindView(R2.id.tv_percent)
    TextView tvPercent;
    @BindView(R2.id.et_price_up)
    EditText etPriceUp;
    @BindView(R2.id.et_price_down)
    EditText etPriceDown;
    private SparseArray<QuotationInfo> mQuotations;
    private int stairPosition;
    private String productId;
    private double close;
    private int buyColorResource;
    private int sellColorResource;
    private int neutralColorResource;
    private double marketPrice;
    private IProductApi iProductApi;
    private String userId;
    private double upPrice;
    private double downPrice;
    private String name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_price_float);
        ButterKnife.bind(this);

        iProductApi = ApiFactory.getInstance().getProductApi();

        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);

        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId()+"";

        buyColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), com.baibei.product.R.color.buyColor, null);
        sellColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), com.baibei.product.R.color.sellColor, null);
        neutralColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), com.baibei.product.R.color.textPrimary, null);

        Intent intent = getIntent();
        stairPosition = intent.getIntExtra("stairPosition", -1);
        close = intent.getDoubleExtra("close", -1);
        marketPrice = intent.getDoubleExtra("last", -1);
        name = intent.getStringExtra("name");

        tvProductName.setText(name);
        tvPriceNew.setText(marketPrice +"");
        tvPriceNew.setTextColor(marketPrice > close ? buyColorResource : (marketPrice == close ? neutralColorResource : sellColorResource));
        tvPercent.setText((marketPrice > close ? "+" : "") + (new BigDecimal(((marketPrice * 1.0f - close * 1.0f) / close * 1.0f) * 100).setScale(2, RoundingMode.DOWN) + "%"));
        tvPercent.setTextColor(marketPrice > close ? buyColorResource : (marketPrice == close ? neutralColorResource : sellColorResource));

        etPriceDown.setText(marketPrice+"");
        etPriceUp.setText(marketPrice+"");

        RxObservable.create(iProductApi.getHomeIndexInfosNew(), this.getClass().getName())
                .subscribe(new ApiDefaultObserver<NewHomeIndexInfo>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(NewHomeIndexInfo homeIndexInfo) {
                        productId = homeIndexInfo.getCategoryList().get(stairPosition).getProductId()+"";
                        PriceFloatActivity.this.close = Rx.parseDouble(homeIndexInfo.getCategoryList().get(stairPosition).getClosePrice());
                        name = homeIndexInfo.getCategoryList().get(stairPosition).getQuoteName();
                        tvProductName.setText(name);

                    }
                });

    }

    @Subscribe
    @Override
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        mQuotations = quotations;
        refresh();
    }

    private void refresh() {
        if (productId == null) return;
        marketPrice = mQuotations.get(Integer.parseInt(productId)).getMarketPrice();
        tvPriceNew.setText(marketPrice +"");
        tvPriceNew.setTextColor(marketPrice > close ? buyColorResource : (marketPrice == close ? neutralColorResource : sellColorResource));
        tvPercent.setText((marketPrice > close ? "+" : "") + (new BigDecimal(((marketPrice * 1.0f - close * 1.0f) / close * 1.0f) * 100).setScale(2, RoundingMode.DOWN) + "%"));
        tvPercent.setTextColor(marketPrice > close ? buyColorResource : (marketPrice == close ? neutralColorResource : sellColorResource));
    }

    @OnClick(R2.id.iv_back)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R2.id.tv_confirm)
    public void onConfirmClicked() {
        upPrice = 0.0;
        downPrice = 0.0;
        if (!etPriceUp.getText().toString().trim().equals("")){
            upPrice = Double.parseDouble(etPriceUp.getText().toString().trim());
        }
        if (!etPriceDown.getText().toString().trim().equals("")){
            downPrice = Double.parseDouble(etPriceDown.getText().toString().trim());
        }
        if (upPrice != 0.0 && upPrice <= marketPrice){
            ToastUtils.showShortToast("设置的价格上限应该高于现价");
            return;
        }
        if (downPrice != 0.0 && downPrice >= marketPrice){
            ToastUtils.showShortToast("设置的价格下限应该低于现价");
            return;
        }
        if (upPrice == 0.0 && downPrice == 0.0){
            ToastUtils.showShortToast("请至少输入一个价格");
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", userId);
                map.put("lowPrice", downPrice == 0.0 ? "" : downPrice +"");
                map.put("topPrice", upPrice == 0.0 ? "" : upPrice +"");
                map.put("productId",productId);
                map.put("productName",name);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                Log.e("resultinfos",s);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(com.baibei.ebec.sdk.BuildConfig.API_BASE_URL + "user/set/product/price")
                        .post(requestBody)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    JSONObject result = new JSONObject(response.body().string());
                    Log.e("resultinfos",result.toString());
                    if (!"SUCCESS".equals(result.optString("code"))){

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast("发送请求失败，请重试");
                            }
                        });
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showShortToast("设置成功");
                            etPriceDown.setText(null);
                            etPriceUp.setText(null);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    @Override
    protected void onDestroy() {
        QuotationManager.getInstance().unregister(this);
        super.onDestroy();
    }
}
